import { createApp, h } from 'vue';
import TradeInReceiptA4 from '@/components/biz/tradeInReceipt/A4.vue';

/**
 * 动态创建并打印组件，打印完成后销毁组件
 * @param component 要打印的组件
 * @param props 组件的props
 * @returns Promise 打印完成后resolve
 */
export const printComponent = (component: any, props: any): Promise<void> => {
  return new Promise((resolve) => {
    // 创建一个临时容器
    const container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.left = '-9999px';
    container.style.top = '-9999px';
    document.body.appendChild(container);

    // 创建应用实例
    const app = createApp({
      setup() {
        return () => h(component, {
          ...props,
          ref: 'printComponent',
          onPrinted: () => {
            // 打印完成后销毁组件和容器
            setTimeout(() => {
              app.unmount();
              document.body.removeChild(container);
              resolve();
            }, 100);
          }
        });
      }
    });

    // 挂载应用
    const vm = app.mount(container);
    
    // 调用组件的print方法
    setTimeout(() => {
      if (vm.$refs.printComponent && typeof vm.$refs.printComponent.print === 'function') {
        vm.$refs.printComponent.print();
      } else {
        console.error('打印组件没有print方法');
        app.unmount();
        document.body.removeChild(container);
        resolve();
      }
    }, 100);
  });
};

/**
 * 打印回收订单凭证
 * @param orderId 订单ID
 * @returns Promise
 */
export const printTradeInReceipt = (orderId: string): Promise<void> => {
  return printComponent(TradeInReceiptA4, { orderId });
};